package wdutil

import (
	"encoding/base64"
	"sync"
	"time"

	uuid "gitee.com/yutiandou/wdtools/wdutil/go.uuid"
)

var sessionMap *(sync.Map)

//NewId 基于当前时间戳和mac地址返回一个16位ID
func NewLocalId() string {
	id := uuid.NewV1()
	b64 := base64.URLEncoding.EncodeToString(id.Bytes()[:12])
	return b64
}

//NewRandomId 返回一个随机的16位ID
func NewRandomId() string {
	id := uuid.NewV4()
	b64 := base64.URLEncoding.EncodeToString(id.Bytes()[:12])
	return b64
}

func init() {
	sessionMap = &sync.Map{}
}

//StartSessionCheck ..开启session清理，每隔frequency秒，删除存储中的无效session信息
func StartSessionCheck(frequency time.Duration) {
	go func() {
		for {
			<-time.After(frequency)
			nowtime := time.Now().Second()
			sessionMap.Range(func(key, value interface{}) bool {
				if value.(int) < nowtime {
					sessionMap.Delete(key)
				}
				return true
			})
		}
	}()
}

//GetSessionID ..获取一个16位长度的sessionID，并给这个session设置一个时常，单位s
func GetSessionID(timeout int) string {
	session := NewRandomId()
	nowtime := time.Now().Second()
	nowtime += timeout
	sessionMap.Store(session, nowtime)
	return session
}

//ValidationSession ..验证这个session是否过期
func ValidationSession(session string) bool {
	if v, ok := sessionMap.Load(session); ok {
		nowtime := time.Now().Second()
		if v.(int) < nowtime {
			sessionMap.Delete(session)
			return false
		}
		return true
	}
	return false
}
